package org.kotboot.ctrl

import org.kotboot.kit.K
import org.kotboot.kit.KMap
import org.kotboot.module.R
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


@RestControllerAdvice
open class BaseCtrl{
    /**
     * ThreadLocal确保高并发下每个请求的request，response都是独立的
     */
    private val currentRequest = ThreadLocal<HttpServletRequest>()
    private val currentResponse = ThreadLocal<HttpServletResponse>()
    private val log = LoggerFactory.getLogger(BaseCtrl::class.java)

    /**
     * 线程安全初始化reque，respose对象
     * @param request
     * @param response
     */
    @ModelAttribute
    fun initReqAndRep(request: HttpServletRequest, response: HttpServletResponse) {
        currentRequest.set(request)
        currentResponse.set(response)
    }


    /**
     * 线程安全
     * @return
     */
    fun request(): HttpServletRequest {
        return currentRequest.get()
    }

    /**
     * 线程安全
     * @return
     */
    fun response(): HttpServletResponse {
        return currentResponse.get()
    }

    fun getParams(): KMap {
        return K.http.castMap(request())
    }


    @ExceptionHandler(Exception::class)
    fun globalExceptionHandler(ex: Exception): R<*> {
        log.info(ex.message)
        return R.ER(ex.message)
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException::class)
    fun methodArgumentException(ex:MethodArgumentTypeMismatchException) : R<*>{
        log.info(ex.message)
        return R.ER(ex.name + " : 参数错误")
    }
}



